package edu.ccut.saturn.manager.bundles.core;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.core.ServiceFactory;

public class ReleaseBundle extends DefaultComponent {

	private static final String DEFAULTVERSIONNUM = "1.0.0";

	private String symbolicName = "";

	private String versionNum = "";

	@Override
	public void execute(IParameterContext parameterContext) {

		symbolicName = (String) parameterContext.getParameterValue(0);
		versionNum = (String) parameterContext.getParameterValue(1);

		String result = "true";

		if ("".equals(symbolicName)) {
			logger.error("bundle symbolicName is null");
			result = "bundle symbolicName is null";
			parameterContext.setParameter(2, result);
			return;
		}

		if ("".equals(versionNum)) {
			versionNum = DEFAULTVERSIONNUM;
		}

		Bundle bundle = this.getBundleBySymbolic(symbolicName);

		try {
			if (bundle != null) {

				bundle.start();
				bundle.update();
				logger.info("[" + symbolicName + "] bundle exist," + "update ["
						+ symbolicName + "] bundle success!");
			} else {

				bundle = ServiceFactory.getBundleService().getBundleContext()
						.installBundle(this.getLocation());

				bundle.start();

				logger.info("[" + symbolicName
						+ "] bundle not exist, install and start ["
						+ symbolicName + "] bundle success!");
			}
		} catch (BundleException e) {
			logger.error("[" + symbolicName
					+ "] bundle not found or bundle not validate!");
			result = "[" + symbolicName + "]  bundle not found!";
		}
		parameterContext.setParameter(2, result);
	}

	private Bundle getBundleBySymbolic(String name) {
		Bundle[] bundles = ServiceFactory.getBundleService().getBundles();

		for (Bundle bundle : bundles) {
			if (bundle.getSymbolicName().equals(name)) {
				return bundle;
			}
		}

		return null;
	}

	private String getLocation() {
		String location = null;
		String releasePath = "";

		Bundle[] bundles = ServiceFactory.getBundleService().getBundles();

		for (Bundle bundle : bundles) {
			String bundlelocation = bundle.getLocation();
			int lastSlash = bundlelocation.lastIndexOf("bundles");
			if (lastSlash != -1) {
				releasePath = bundlelocation.substring(0, lastSlash + 7);
				break;
			}
		}
		location = releasePath + "\\plugins\\" + this.symbolicName + "_"
				+ this.versionNum + ".jar";
		return location;
	}

}